package com.zim.aliot.controller;

import java.util.Base64;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.iot.model.v20180120.QueryDeviceDetailRequest;
import com.aliyuncs.iot.model.v20180120.QueryDeviceDetailResponse;
import com.aliyuncs.iot.model.v20180120.RegisterDeviceRequest;
import com.aliyuncs.iot.model.v20180120.RegisterDeviceResponse;
import com.zim.aliot.config.AliIotConfig;
import com.zim.aliot.enums.ResultEnum;
import com.zim.aliot.exception.IotApiException;
import com.zim.aliot.service.AliClientService;
import com.zim.aliot.service.CommandService;
import com.zim.aliot.service.MessageService;
import com.zim.aliot.util.ResultVOUtils;
import com.zim.aliot.vo.ResultVO;
import com.zim.analysis.SaiKa;
import com.zim.analysis.util.FormatUtils;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/device")
@Slf4j
public class DeviceController {
    private final Base64.Decoder decoder = Base64.getDecoder();
    
    @Autowired 
    private DefaultAcsClient defaultAcsClient;
    
    @Autowired
    private AliIotConfig aliIotConfig;
    
    @Autowired
    private AliClientService aliClientService;
    
    @Autowired
    private MessageService messageService;
    
    @Autowired
	private CommandService commandService;
 
    @RequestMapping(value = "/detail", method = { RequestMethod.POST,
            RequestMethod.GET }, produces = "application/json;charset=UTF-8")
    public ResultVO<Object> detail(@RequestParam(name = "device_name",defaultValue="",required=true) String deviceName) {
        if (StringUtils.isEmpty(deviceName)) {
            log.error("【设备详情】device_name为空");
            throw new IotApiException(ResultEnum.PARAM_ERROR.getCode(), "device_name为空");
        }
        QueryDeviceDetailRequest request = new QueryDeviceDetailRequest();
        request.setProductKey(aliIotConfig.getProductKey());
        request.setDeviceName(deviceName);
        
        try {
            QueryDeviceDetailResponse response = defaultAcsClient.getAcsResponse(request);
            if (response != null && response.getSuccess() != false) {
                return ResultVOUtils.success(response.getData());
            } else {
                log.error("【查询设备失败】！requestId:" + response.getRequestId() + "原因：" + response.getErrorMessage());
                return ResultVOUtils.error(ResultEnum.ERROR.getCode(),response.getErrorMessage());
            }
        } catch (ClientException e) {
            log.error("【设备详情】:{}",e.getMessage());
            return ResultVOUtils.error(ResultEnum.ERROR.getCode(), e.getMessage());
        } 
          
    }
    
    @RequestMapping(value = "/regist", method = { RequestMethod.POST,
            RequestMethod.GET }, produces = "application/json;charset=UTF-8")
    public ResultVO<Object> register(@RequestParam(name = "device_name",defaultValue="",required=true) String deviceName) {
        if (StringUtils.isEmpty(deviceName)) {
            log.error("【设备注册】device_name为空");
            throw new IotApiException(ResultEnum.PARAM_ERROR.getCode(), "device_name为空");
        }
        RegisterDeviceRequest request = new RegisterDeviceRequest();
        request.setProductKey(aliIotConfig.getProductKey());
        request.setDeviceName(deviceName);
        
        try {
            RegisterDeviceResponse response = defaultAcsClient.getAcsResponse(request);
            if (response != null && response.getSuccess() != false) {
                return ResultVOUtils.success(response.getData());
            } else {
                log.error("【设备注册失败】！requestId:" + response.getRequestId() + "原因：" + response.getErrorMessage());
                return ResultVOUtils.error(ResultEnum.ERROR.getCode(),response.getErrorMessage());
            }
        } catch (ClientException e) {
            log.error("【设备注册】:{}",e.getMessage());
            return ResultVOUtils.error(ResultEnum.ERROR.getCode(), e.getMessage());
        }
        
    }
    
    @RequestMapping("/upgrade")
    public ResultVO<Object> upgrade(@RequestParam(name = "car_unique_id",defaultValue="",required=true)
    		String car_unique_id,@RequestParam(name = "version",defaultValue="",required=true) String version){
    	 if (StringUtils.isEmpty(car_unique_id) || StringUtils.isEmpty(version)) {
             log.error("【设备升级,参数不能为空】car_unique_id:{},version:{}",car_unique_id,version);
             throw new IotApiException(ResultEnum.PARAM_ERROR.getCode(), "参数不能为空");
         }
    	 long time = new Date().getTime();
    	 boolean resUpgrade = commandService.commandAction(car_unique_id, "", "UPGRADE", 0, time, 0,version,"");
 		 if(resUpgrade) {
 			return ResultVOUtils.success();
 		 }else {
 			return ResultVOUtils.error(ResultEnum.ERROR.getCode(),"升级失败");
 		 }

    	
    }
    
    @GetMapping(value = "cmd/{id}")
    public void doCommandAction(@PathVariable("id") int id) {
         SaiKa terminal = new SaiKa();
         String deviceName = "0000000B121180106843";
        byte[] bt = null;
        try {
            switch (id) {
            case 1:
                bt= terminal.ignite(deviceName, true);
                break;
            case 2:
                bt= terminal.ignite(deviceName, false);
                break;
            case 3:
                bt= terminal.lock(deviceName, true);
                break;
            case 4:
                bt= terminal.lock(deviceName, false);
                break;
            case 5:
                bt = terminal.whistle(deviceName, true);
                break;
            case 6:
                bt = terminal.password(deviceName, "bluetoot");
                break;
            case 7:
                bt= terminal.photo(deviceName);
                break;
            case 8:
                bt= terminal.rent(deviceName, 1);
                break;  
            default:
                break;
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //System.out.println(new String(bt));
        //byte[] test = new byte[]{0x13, 0x12};
        System.out.println(FormatUtils.byteToHexStr(bt));

        System.err.println(aliClientService.pubMessage(bt, deviceName));
    }
    
    @GetMapping(value = "jiexi")
    public void jiexi() {
        String string= "qgAAAAsSEYAQaEOiACkABBgSGBZBOQAAAAcRNUUlRCI0YBYKAAAAAAAAAAAAAAAAAAAAAACcHx+q";
        try {
            System.err.println(FormatUtils.byteToHexStr(decoder.decode(string)));
            messageService.messageHandle(decoder.decode(string));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
}
